var App = App||{};
App.init = function(){ App.Admin.init(); };
App.Admin = {};

App.Admin.init = function(){
	var self = this;
	this.loadUsers();
	this.loadProjects();
	
	this.userTemplate = $("#userTemplate").template();
	this.userEditTemplate = $("#userEditTemplate").template();
	
	this.projectTemplate = $("#projectTemplate").template();
	this.projectEditTemplate = $("#projectEditTemplate").template();
	
	$('#wrapper .admin-pane .admin-table')
		.delegate('tbody tr', 'click', function(e){									// start edit action
			e.stopPropagation();
			self.startEdit.call(self, $(this)); 
		})
		.delegate('tbody .in-edit input', 'keyup', function(e){						// save row on enter
			e.stopPropagation();
			var key = e.keyCode, row = $(this).closest('.in-edit');
			if (key == 13) self.saveEdit.call(self, row);
		})
		.delegate('tbody .actions .icon', 'click', function(e){						// delete, edit (save/cancel) actions
			e.stopPropagation();
			var icon = $(this), action = icon.data('action'), row = icon.closest('.row');
			self.rowActionHandler.call(self, row, action); 
		})
		.delegate('tfoot .icon-save', 'click', function(e){							// add row action
			e.stopPropagation();
			self.rowActionHandler.call(self, $(this).closest('.row'), 'add'); 
		});
	$('body').bind('click', $.proxy(this.cancelAll, this));							// cancel edit on body click
	$(document).bind('keyup', $.proxy(this.onKeyUp, this));							// cancel edit on escape
};



/*** ACTION HANDLERS ****************************************************************************************/
App.Admin.startEdit = function(row){
	if (row.is('.in-edit')) return;
	this.cancelAll();																// cancel edit on all the other rows
	var rowData = row.data(), tplItem = row.tmplItem();								// Get template item associated with DIV
	if (rowData.type == 'user') tplItem.tmpl = this.userEditTemplate;				// Change template to compiled template
	else tplItem.tmpl = this.projectEditTemplate;									// Change template to compiled template
	tplItem.update();																// Re-render template
	$(tplItem.nodes).find('input')[0].select();
};


App.Admin.cancelEdit = function(row){
	var rowData = row.data(), tplItem = row.tmplItem();
	if (rowData.type == 'user') tplItem.tmpl = this.userTemplate;
	else tplItem.tmpl = this.projectTemplate;
    tplItem.update();
};

App.Admin.cancelAll = function(){
	var rows = $('#wrapper .admin-table tr.in-edit'), i=0, row;
	for (; row = rows[i++] ;) this.cancelEdit($(row));
};

App.Admin.saveEdit = function(row){
	var rowData = row.data(), type = rowData.type.ucfirst(), url = 'update'+type, data = { id: rowData.id };
	
	if (type == 'User'){												// save user
		data.login = row.find('input[name=login]').val();
		data.email = row.find('input[name=email]').val();
		data.status = row.find('select[name=status]').val();
	}
	else {																// save project
		data.name = row.find('input[name=name]').val(); 
		data.archive = row.find('input[name=archive]')[0].checked; 
	}
	
	$.ajax({ url: url, context: this, data: data })
	.success(function(data){ 
		if (!data || data.result == 'error'){ App.Error(data); return; }
		msgbox(type + ' details have been updated');
		$.extend(true, row.tmplItem().data, data);
		this.cancelEdit(row);
	});
};

App.Admin.addRow = function(row){
	var rowData = row.data(), type = rowData.type.ucfirst(), url = 'add'+type, data = { };
	
	if (type == 'User'){												// save user
		data.login = row.find('input[name=login]').val();
		data.email = row.find('input[name=email]').val();
		data.status = row.find('select[name=status]').val();
	}
	else {																// save project
		data.name = row.find('input[name=name]').val(); 
		data.archive = row.find('input[name=archive]')[0].checked; 
	}
	
	$.ajax({ url: url, context: this, data: data })
	.success(function(data){ 
		if (!data || data.result == 'error'){ App.Error(data); return; }
		msgbox(type + ' have been added');
		$.extend(true, row.tmplItem().data, data);		
		row.find('input,select').val('');
		this['load'+type+'s']();
	});
};



App.Admin.deleteRowSubmit = function(type, row){
	var rowData = row.data(), type = rowData.type.ucfirst(), url = 'delete'+type;
	$.ajax({ url: url, context: this, data: { id: rowData.id } })
	.success(function(data){ row.fadeOut(500, function(){row.remove();}); msgbox(type + ' has been removed'); });
};
App.Admin.deleteRow = function(row){
	var rowData = row.data(), type = rowData.type, name = row.find('.td-name').text();
	new Window({ content: 'Are you sure you want to remove '+type+': <b>'+name+'</b>?', title: 'Remove '+type, modal: true, disposable: true, 
		buttons: [{ text: 'Yes', cls: 'submit', scope: this, fn: function(){ this.deleteRowSubmit(type, row); }}, { text: 'No' }]
	}).show(); 
};

App.Admin.resetPasswordSubmit = function(row){
	var rowData = row.data(), name = row.find('.td-name').text();
	$.ajax({ url: 'updateUser', context: this, data: { id: rowData.id, password: '' } })
	.success(function(data){ msgbox(name+'\'s password has been reset'); });
};
App.Admin.resetPassword = function(row){
	var name = row.find('.td-name').text();
	new Window({ content: 'Are you sure you want to reset password for <b>'+name+'</b>?', title: 'Reset password', modal: true, disposable: true, 
		buttons: [{ text: 'Yes', cls: 'submit', scope: this, fn: function(){ this.resetPasswordSubmit(row); }}, { text: 'No' }]
	}).show(); 
};


App.Admin.rowActionHandler = function(row, action){
	if (action == 'cancel') this.cancelEdit(row);
	else if (action == 'save') this.saveEdit(row);
	else if (action == 'delete') this.deleteRow(row);
	else if (action == 'add') this.addRow(row);
	else if (action == 'resetpass') this.resetPassword(row);
};


App.Admin.onKeyUp = function(e){
	var key = e.keyCode, ESC = 27;
	if (key == ESC) this.cancelAll();
};

/*** ACTION HANDLERS ****************************************************************************************/



App.Admin.loadUsers = function(){ $.ajax({ url: "users", context: this }).success(function(data){ $('#usersList tbody').html($.tmpl(this.userTemplate, data)); }); };

App.Admin.loadProjects = function(){ $.ajax({ url: "projects", context: this }).success(function(data){ $('#projectsList tbody').html($.tmpl(this.projectTemplate, data)); }); };


